<?php
/**
 *OrderRefundServices
 * @author tan bing
 * @date 2021-11-15 17:53
 */


namespace Modules\Order\Services\Admin;


use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Modules\Order\Entities\Order;
use Modules\Order\Entities\User;
use Modules\Order\Entities\UserCoupon;

class OrderRefundServices extends BaseService
{
    private Request $request;

    public function __construct(Request $requset)
    {
        $this->request = $requset;
    }

    /**
     * 取消订单审核并退款
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object
     * @throws \Throwable
     * @author tan bing
     * @date 2021-11-16 17:41
     */
    public function refundOrder()
    {
        $orderId = $this->request->post('id');
        $refundPrice = $this->request->post('refund_price');
        $action = $this->request->post('action');
        $order = Order::query()->where(['id' => $orderId, 'apply_delete' => 1, 'is_delete' => 0])->first();
        if(!$order)
            throw new \Exception('订单不存在，请刷新页面后重试');

        switch ($action) {
            case 1 :
                // 同意取消订单并退款
                $order->order_status = 4;
                break;
            case 2:
                // 拒绝取消订单     --改为未申请取消状态
                $order->apply_delete = 0;
                if(!$order->save())
                    throw new \Exception('操作失败');

                // TODO 给用户发送消息通知
                return $order;
                break;
            default:
                throw new \Exception('未知操作');
                break;
        }
        DB::beginTransaction();
        try {
            $user     = User::where(['id' => $order->user_id])->first();
            // 用户积分恢复
            $integral = json_decode($order->integral)->forehead_integral;
            if ($integral > 0) {
                $user->integral += $integral;
            }
            if (!$order->save())
                throw new \Exception("订单取消失败");

            $order->user = $user;

            if($order->user_coupon_id) {
                $userCoupon = UserCoupon::where('user_coupon_id', $order->user_coupon_id)->first();
                $userCoupon->is_use = 0;
                if(!$userCoupon->save())
                    throw new \Exception('取消订单失败，优惠券退回失败');
            }

            // 退款
            $refundServices = new \Modules\Order\Services\Common\RefundServices();
            $refundServices->refundHandle($order, $order->order_no, $order->pay_price, $order->pay_type);
            $refundServices->goodsStockAdNum($order);

            // TODO 给用户发送消息通知

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            throw new \Exception($e->getMessage());
        }

        return $order;
    }


}